import { outLogin } from '@/services/user';
import { ResponseCode } from '@/utils/request';
import { LogoutOutlined } from '@ant-design/icons';
import { Avatar, Dropdown, message, notification, Space, Spin } from 'antd';

import React, { useCallback } from 'react';
import { history, useModel } from '@umijs/max';
import { MenuInfo } from 'rc-menu/lib/interface';
import { LOGIN_FROM_TAG, LOGIN_PATH } from '@/constant';

export type GlobalHeaderRightProps = {
  menu?: boolean;
};

/**
 * 退出登录，并且将当前的 url 保存
 * sessionId设置httpOnly前端无法读写，需要请求后端登出接口才能实现真正的登出
 */
const loginOut = async () => {
  const { code, message: msg } = await outLogin();
  if (code === ResponseCode.Fail) {
    notification.error({ message: msg });
    return;
  }
  message.info('清除登入态成功');
  if (window.location.pathname !== LOGIN_PATH) {
    window.sessionStorage.setItem(LOGIN_FROM_TAG, window.location.pathname);
  }
  history.replace({
    pathname: '/verify/login',
  });
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = () => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        loginOut();
        setInitialState((s) => ({ ...s, currentUser: undefined }));
        return;
      }
    },
    [setInitialState],
  );

  const loading = (
    <span>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.username) {
    return loading;
  }

  return (
    <Dropdown
      menu={{
        items: [
          {
            label: (
              <>
                <LogoutOutlined />
                退出登录
              </>
            ),
            key: 'logout',
          },
        ],
        onClick: onMenuClick,
      }}
    >
      <Space align="center">
        <Avatar size="small" src={currentUser.avatarImage} alt="avatar" />
        <span>{currentUser.username}</span>
      </Space>
    </Dropdown>
  );
};

export default AvatarDropdown;
